(function ($) {
    "use strict";

    var URL = {
        country: {
            getCountryList: "/rest/country/getCountryList?"
        },
        location: {
            getCityList: "/rest/location/getCityList?province_Id={0}",
            getCountyList: "/rest/location/getCountyList?city_Id={0}",
            getProvinceList: "/rest/location/getProvinceList?country_Id={0}"
        },
        patient: {
            checkIcNo: "/rest/patient/checkIcNo?patient_Id={1}&icNo={0}",
            createPatient: "/rest/patient/createPatient?",
            getProcessedPatients: "/rest/patient/getProcessedPatients?{0}",
            getProcessedPatientsCount: "/rest/patient/getProcessedPatientsCount?like={0}",
            getPatient: "/rest/patient/getPatient?patient_Id={0}",
            getPatients: "/rest/patient/getPatients?{0}",
            getPatientsCount: "/rest/patient/getPatientsCount?status={0}&like={1}",
            setInitial: "/rest/patient/setInitial?patient_Id={0}",
            setNeedSolution: "/rest/servreq/setNeedSolution?servReq_Id={0}&user_Id={1}",
            setNew: "/rest/patient/setNew?patient_Id={0}",
            setNeedOpe: "/rest/servreq/setNeedOpe?",//
            setNoOpeNeeded: "/rest/servreq/setNoOpeNeeded?",//
            setNeedDiag: "/rest/servreq/setNeedDiag?",//
            setRetNON: "/rest/servreq/setRetNON?",//
            setRetByMedAdmin: "/rest/servreq/setRetByMedAdmin?",//
            setRetBySpecia: "/rest/servreq/setRetBySpecia?",//
            // updatePatient2: "/rest/patient/updatePatient2?{0}"
            // updatePatient1: "/rest/patient/updatePatient1?{0}",
            updatePatient1: "/rest/patient/updatePatient1?",
            updatePatient2: "/rest/patient/updatePatient2?",
            sharePatient:"/rest/chat/createChatMessageSharingPatient?"
        },
        race: {
            getRaces: "/rest/race/getRaces?"
        },
        servreq: {
            getServReqs: "/rest/servreq/getServReqs?{0}",
            getServReqsCount: "/rest/servreq/getServReqsCount?status={0}"
        },
        user: {
            getUsers: "/rest/user/getUsers?userRole={0}&like={1}&pageNo={2}&pageSize={3}"
        },
        const: {
            getDiagConsts: "/rest/const/getDiagConsts?"
        },
        diseaseType: {
            getDiseaseType: "/rest/diseasetype/getDiseaseTypeList?"
        }
    };

    var imageSrc = null;

    app.controller("PatientIndexCtrl", PatientIndexCtrl);
    app.controller("PatientDetailsCtrl", PatientDetailsCtrl);
    app.controller("AddPatientCaseCtrl", AddPatientCaseCtrl);
    app.factory("PatientCaseFactory", PatientCaseFactory);
    app.controller("PatientServReqController", PatientServReqController);

// index
    function PatientIndexCtrl($compile, $modal, $scope, $translate, toaster, RESTService, $filter, $stateParams) {
        // init
        var modelInstance, modelInstance1, rowCountInstance;
        $scope.servReq_Id = $stateParams.servReq_Id;
        $scope.rowCount = 0;
        $scope.like = '';
        $scope.current = $scope.$state.current.url;
        $scope.open = function (attrs, data, handler) {
            var instanceTemp = $modal.open(angular.extend({
                backdrop: "static",
                controller: "ModalInstanceCtrl",
                resolve: {
                    items: function () {
                        return [Object(data)];
                    }
                },
                scope: $scope
            }, attrs));

            if (undefined !== handler && "function" === typeof $scope[handler]) {
                $scope[handler]();
            }
            if (modelInstance === undefined) {
                modelInstance = instanceTemp;
            } else {
                modelInstance1 = instanceTemp;
            }

            instanceTemp.result.then(function () {
            }, function () {
                // cancel event
                if (modelInstance == instanceTemp) {
                    modelInstance = undefined; // check if this is first popup
                }
            });

        };

        $scope.flag_needOpe = false;
        $scope.flag_setNoOpeNeeded = false;
        $scope.flag_setNew = false;
        $scope.flag_imageDiag = false;
        $scope.flag_opeSche = false;
        $scope.setNeedOpe = function () {
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flat_opeSche = false;
            $scope.flag_needOpe = true;
        };
        $scope.setNoOpeNeeded = function () {
            $scope.flag_needOpe = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = false;
            $scope.flag_setNoOpeNeeded = true;
        };
        $scope.setNew = function () {
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = false;
            $scope.flag_setNew = true;
        };
        $scope.imageDiag = function () {
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_opeSche = false;
            $scope.flag_imageDiag = true;
        };
        $scope.opeSche = function () {
            $scope.flag_needOpe = false;
            $scope.flag_setNoOpeNeeded = false;
            $scope.flag_setNew = false;
            $scope.flag_imageDiag = false;
            $scope.flag_opeSche = true;
        };


        // get no. of patients
        (rowCountInstance = function (handler) {
            var url = ("/filter" === $scope.$state.current.url || "/diagnosis" === $scope.$state.current.url)
                ? URL.servreq.getServReqsCount : URL.patient.getPatientsCount;
            RESTService.getResponse(url.format($scope.filterStatus, $scope.like)).then(
                function (response) {
                    $scope.rowCount = ~~response[0].count;
                    handler && handler();
                });
            RESTService.getResponse("/rest/servreq/getServReqs?status=all&like=" + $scope.like)
                .then(function (response) {
                    $scope.servReqs = response;
                });
        })();

        // get patients with pagination
        $scope.dtOptions = {
            aaSorting: [],
            bFilter: false,
            bLengthChange: false,
            bSort: false,
            bStateSave: false,
            oLanguage: {
                // sUrl: "//cdn.datatables.net/plug-ins/1.10.11/i18n/{0}.json".format("Cn" === $scope.locale ? "Chinese" : "English")
                sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
            },
            processing: true,
            serverSide: true,
            sAjaxDataProp: "data",
            ajax: function (data, callback) {
                // prepare query variables
                var params = {
                    status: $scope.filterStatus,
                    like: $scope.like,
                    pageNo: data.start / data.length + 1,
                    pageSize: data.length
                };
                var sort = [], i;

                if (0 !== data.order.length) {
                    for (i in data.order) {
                        if (data.order.hasOwnProperty(i)) {
                            sort.push({
                                property: data.columns[data.order[i].column].data,
                                direction: data.order[i].dir.toUpperCase()
                            });
                        }
                    }

                    if (0 !== sort.length) {
                        params.sort = angular.toJson(sort);
                    }
                }

                if (3 <= data.search.value.length) {
                    params.filter = data.search.value;
                }
                // transmit to server
                var url = "/patcase" === $scope.$state.current.url ? URL.patient.getPatients : URL.servreq.getServReqs;
                RESTService.getResponse(url.format($.param(params))).then(function (response) {
                    $scope.$parent.patients = [];
                    angular.forEach(response, function (item) {
                        item.No = $scope.$parent.patients.length + (params.pageNo * params.pageSize) - 9;
                        $scope.$parent.patients.push(item);
                    });
                    callback({
                        aaData: [],
                        draw: data.draw,
                        recordsTotal: $scope.rowCount,
                        recordsFiltered: $scope.rowCount
                    });
                    $scope.dtInstance.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                });
            },
            fnCreatedRow: function (row) {
                $compile(row)($scope);
            },
            fnInitComplete: function () {
                $scope.$parent.dtInstance = this.fnSetFilteringDelay();
            }
        };


        // $scope.$watch("filterStatus", function (newValue) {
        //     if (undefined !== newValue && undefined !== $scope.dtInstance) {
        //         rowCountInstance(function () {
        //             $scope.dtInstance.DataTable().ajax.reload();
        //         });
        //     }
        // });
        //
        // $scope.$watch("like", function (newValue) {
        //     if (undefined !== newValue && undefined !== $scope.dtInstance) {
        //         rowCountInstance(function () {
        //             $scope.dtInstance.DataTable().ajax.reload();
        //         });
        //     }
        // });


        $scope.filtlike = function(){
            rowCountInstance(function () {
                $scope.dtInstance.DataTable().ajax.reload();
            });
        };


        // $scope.$watch('selectLang', function(nVal, oVal){
        //     console.log('new value :',nVal);
        //     console.log('old value :',oVal);
        //     // $scope.dtOptions.oLanguage.sUrl = "//cdn.datatables.net/plug-ins/1.10.11/i18n/{0}.json".format("English" === nVal ? "English" : "Chinese")
        //     if(nVal != oVal){
        //         window.location.reload();
        //     }
        // })

        $scope.diagConsts = [
            {key: "none", type: "diag", name: $filter('translate')('diagconsts.none.name')},
            {key: "mild", type: "diag", name: $filter('translate')('diagconsts.mild.name')},
            {key: "serious", type: "diag", name: $filter('translate')('diagconsts.serious.name')}
        ];

        $scope.diseaseType = [];
        RESTService.getResponse(URL.diseaseType.getDiseaseType).then(function (response) {
            $scope.diseaseType = response;
        });

        RESTService.getResponse(URL.user.getUsers.format("Specialist", "", 1, 1000)).then(
            function (response) {
                $scope.specialists = response;
            });

        $scope.onSetSelection = function ($event, status, servReq_Id, input) {
            console.log($event);
            var params;
            switch (status) {
                case "RetByMedAdmin":
                case "RetNON":
                    params = {
                        servReq_Id: servReq_Id,
                        desc: input.desc
                    };
                    // input = $.param(angular.extend({
                    //     desc: ""
                    // }, input));
                    break;
                // case "RetNON":
                //     params = {
                //         servReq_Id : servReq_Id,
                //         desc : input.desc
                //     }
                //     // input = $.param(angular.extend({
                //     //     desc: ""
                //     // }, input));
                //     break;
                case "RetBySpecia":
                    params = {
                        servReq_Id: servReq_Id,
                        diag_Desc: input.diag_Desc
                    }
                    // input = $.param(angular.extend({
                    //     diag_Desc: ""
                    // }, input));
                    break;
                case "NeedDiag":
                    if (1 > input || undefined === _.findWhere($scope.specialists, {userId: ~~input})) {
                        return toaster.pop("error", $translate.instant("business.patcase.send_for_diagnosis_specialist_error"));
                    }
                    ;
                    params = {
                        servReq_Id: servReq_Id,
                        user_Id: input
                    }
                    break;
                default:
            }

            $($event.currentTarget).button("loading");

            RESTService.postResponse(URL.patient["set" + status], params).then(
                function () {
                    rowCountInstance(function () {
                        $scope.dtInstance.DataTable().ajax.reload();
                        modelInstance && modelInstance.close();
                        modelInstance1 && modelInstance1.close();
                        modelInstance = modelInstance1 = undefined; // clear instances when done
                    });
                });
        };

        $scope.onSetStatus = function ($event, status, patientId, input) {
            // setNeedOpe: "/rest/servreq/setNeedOpe?servReq_Id={0}&{1}",
            // setNoOpeNeeded: "/rest/servreq/setNoOpeNeeded?servReq_Id={0}&{1}",
            var params;
            switch (status) {
                case "NeedOpe":
                    params = {
                        servReq_Id: patientId,
                        diag_SpinalCord: input.diag_SpinalCord,
                        diseaseType: input.diseaseType,
                        diag_Calcify: input.diag_Calcify,
                        diag_Slip: input.diag_Slip,
                        diag_Desc: input.diag_Desc
                    }
                    // input = $.param(angular.extend({
                    //     diag_SpinalCord: "",
                    //     diseaseType: "",
                    //     diag_Calcify: "",
                    //     diag_Slip: "",
                    //     diag_Desc: ""
                    // }, input));
                    break;
                case "NoOpeNeeded":
                    params = {
                        servReq_Id: patientId,
                        diag_Desc: input.diag_Desc
                    }
                    // input = $.param(angular.extend({
                    //     diag_Desc: ""
                    // }, input));
                    break;
                default:
            }

            $($event.currentTarget).button("loading");
            RESTService.postResponse(URL.patient["set" + status], params).then(
                function () {
                    rowCountInstance(function () {
                        $scope.dtInstance.DataTable().ajax.reload();
                        modelInstance && modelInstance.close();
                        modelInstance1 && modelInstance1.close();
                    });
                    $($event.currentTarget).button("reset");
                });
        };

        // share case
        $scope.sharePatient = function(a, b){
            var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
            var params = {
                patient_Id:patient_Id
                ,friendId:b
            }
            console.log(params);
            RESTService.postResponse(URL.patient.sharePatient, params).then(
                function (suc) {
                    console.log(suc);
                });
        }
    }

// form
    function PatientDetailsCtrl($scope, $rootScope, $translate, toaster, RESTService, $filter) {
        if ($scope.selectLang != 'English') {
            $scope.styleFix = {
                'cursor': 'default',
                'min-width': '54px'
            }
        } else {
            $scope.styleFix = {
                'cursor': 'default',
                'min-width': '124px'
            }
        }
        $scope.patient = {};
        $scope.init = function (patient_Id) {
            // init model
            $scope.isNew = patient_Id == 0; // patient_Id$.isEmptyObject($scope.selected.item);
            $scope.isEdit = false;

            if (patient_Id > 0) {
                RESTService.getResponse(URL.patient.getPatient.format(patient_Id)).then(
                    function (response) {
                        $scope.patient = response[0];
                    }
                );
            }
            else {
                $scope.patient = angular.extend({ // defaults
                    history_HighBlood: 0,
                    history_HighBlood_Desc: "",
                    history_Diabete: 0,
                    history_Diabete_Desc: "",
                    history_Cardiov: 0,
                    history_Cardiov_Desc: "",
                    history_Epidemic: 0,
                    history_Epidemic_Desc: "",
                    history_Surgery: 0,
                    history_Surgery_Desc: "",
                    history_Allergy: 0,
                    history_Allergy_Desc: "",
                    history_Smoke: 0,
                    history_Smoke_Desc: "",
                    history_Drinking: 0,
                    history_Drinking_Desc: "",
                    history_Chem: 0,
                    history_Chem_Desc: "",
                    history_EPIArea: 0,
                    history_EPIArea_Desc: "",
                    history_Other: 0,
                    history_Other_Desc: "",
                    _user: {
                        icCardFile: "",
                        realName: "",
                        icNo: "",
                        gender: "male",
                        race_Name: "",
                        email: "",
                        race_Id: 1,
                        birth_Year: '',
                        birth_Month: '',
                        occupation: '',
                        workPlace: '',
                        marriage: "single",
                        telephone: "",
                        mobile_Phone: "",
                        emerg_Contact: "",
                        emerg_Contact_Mobile: "",
                        photo_File: "",
                        _country: {country_Id: 38, country_Cn_Name: "中国", country_En_Name: "China"},
                        _province: {location_Id: 110000, loca_Cn_Name: "北京市", loca_En_Name: "Beijing"},
                        _city: {location_Id: 110101, loca_Cn_Name: "东城区", loca_En_Name: "DongCheng"},
                        _county: {location_Id: 0, loca_Cn_Name: "", loca_En_Name: ""}
                    }
                }, $scope.selected.item);
            }

            // $scope.$parent.patient._user.icNo = $.trim($scope.patient._user.icNo); // returned data contains spaces =O

            // load data
            $scope.gender = [
                {
                    value: "male",
                    displayNameEn: $translate.instant('user.gender.male'),
                    displayNameCn: $translate.instant('user.gender.male')
                },
                {
                    value: "female",
                    displayNameEn: $translate.instant('user.gender.female'),
                    displayNameCn: $translate.instant('user.gender.female')
                }
            ];
            $scope.marriage = [
                {
                    value: "single",
                    displayNameEn: $translate.instant('user.marriage.single'),
                    displayNameCn: $translate.instant('user.marriage.single')
                },
                {
                    value: "married",
                    displayNameEn: $translate.instant('user.marriage.married'),
                    displayNameCn: $translate.instant('user.marriage.married')
                },
                {
                    value: "widowed",
                    displayNameEn: $translate.instant('user.marriage.widowed'),
                    displayNameCn: $translate.instant('user.marriage.widowed')
                }
            ];
            RESTService.getResponse(URL.race.getRaces).then(
                function (response) {
                    $scope.races = response;
                });
            RESTService.getResponse(URL.country.getCountryList).then(
                function (response) {
                    $scope.countries = response;
                });

            // watch models
            $scope.$watch("patient._user.icNo", function (newValue) {
                if (undefined !== newValue) {
                    $scope.patient.icNo = newValue;
                }
            });
            $scope.$watch("patient._user.realName", function (newValue) {
                if (undefined !== newValue) {
                    $scope.patient.realName = newValue;
                }
            });

            $scope.$watch("patient._user._country", function (newValue) {
                if (angular.isObject(newValue)) {
                    RESTService.getResponse(URL.location.getProvinceList.format(newValue["country_Id"])).then(
                        function (response) {
                            $scope.provinces = response;
                        });
                }
            });
            $scope.$watch("patient._user._province", function (newValue) {
                if (angular.isObject(newValue)) {
                    $scope.patient._user.location_Province = newValue["location_Id"];
                    $scope.patient._user.location_City = "";
                    $scope.patient._user.location_County = "";
                    RESTService.getResponse(URL.location.getCityList.format(newValue["location_Id"])).then(
                        function (response) {
                            $scope.patient._user._city = "";
                            $scope.patient._user._county = "";
                            $scope.cities = response;
                        });
                }
            });
            $scope.$watch("patient._user._city", function (newValue) {
                if (angular.isObject(newValue)) {
                    $scope.patient._user.location_City = newValue["location_Id"];
                    $scope.patient._user.location_County = "";
                    RESTService.getResponse(URL.location.getCountyList.format(newValue["location_Id"])).then(
                        function (response) {
                            $scope.patient._user._county = "";
                            $scope.counties = response;
                        });
                }
            });
            $scope.$watch("patient._user._county", function (newValue) {
                if (angular.isObject(newValue)) {
                    $scope.patient._user.location_County = newValue["location_Id"];
                }
            });
        }

        // create new or update patient
        $scope.submit = function ($event) {
            // if (window.Parsley && !$($event.currentTarget).parsley({ excluded: "[disabled]" }).validate()) {
            //     return false;
            // }

            $scope.patient.icCardFile = $scope.patient._user.icCardFile;
            $scope.patient.icNo = $scope.patient._user.icNo;
            $scope.patient.gender = $scope.patient._user.gender;
            $scope.patient.race_Name = $scope.patient._user.race_Name;
            $scope.patient.email = $scope.patient._user.email;
            $scope.patient.race_Id = $scope.patient._user.race_Id;
            $scope.patient.birth_Year = $scope.patient._user.birth_Year;
            $scope.patient.birth_Month = $scope.patient._user.birth_Month;
            $scope.patient.occupation = $scope.patient._user.occupation;
            $scope.patient.workPlace = $scope.patient._user.workPlace;
            $scope.patient.marriage = $scope.patient._user.marriage;
            $scope.patient.telephone = $scope.patient._user.telephone;
            $scope.patient.mobile_Phone = $scope.patient._user.mobile_Phone;
            $scope.patient.emerg_Contact = $scope.patient._user.emerg_Contact;
            $scope.patient.emerg_Contact_Mobile = $scope.patient._user.emerg_Contact_Mobile;
            $scope.patient.location_Address = $scope.patient._user.location_Address;
            $scope.patient.photo_File = $scope.patient._user.photo_File;

            if (angular.isObject($scope.patient._user._country)) {
                $scope.patient.location_Country = $scope.patient._user._country["country_Id"];
            }

            if (angular.isObject($scope.patient._user._province)) {
                $scope.patient.location_Province = $scope.patient._user._province["location_Id"];
            }

            if (angular.isObject($scope.patient._user._city)) {
                $scope.patient.location_City = $scope.patient._user._city["location_Id"];
            }

            if (angular.isObject($scope.patient._user._county)) {
                $scope.patient.location_County = $scope.patient._user._county["location_Id"];
            }

            // transmit to server
            var $button = $($event.currentTarget).find("button[type=submit]").button("loading");
            var handler = function (response) {
                if (angular.isObject(response[0])) {
                    // update user
                    $scope.patient._user.patient_Id = response[0]["patient_Id"];
                    // RESTService.getResponse(URL.patient.updatePatient1.format($.param($scope.patient._user))).then(
                    //     function (response) {
                    //         if (response.length > 0) {
                    //             // reload page
                    //             $scope.$state.reload();
                    //             $scope.cancel();
                    //         }
                    //     });
                    RESTService.postResponse(URL.patient.updatePatient1, $scope.patient._user).then(
                        function (response) {
                            if (response.length > 0) {
                                // reload page
                                $scope.$state.reload();
                                $scope.cancel();
                            }
                        });
                }
                $button.button("reset");
            };
            if ($scope.isNew) {
                // var param = $.param($scope.patient).replace(/null/gi, "");
                // create patient
                RESTService.postResponse(URL.patient.createPatient, $scope.patient).then(
                    function (response) {
                        if (response.length > 0) {
                            $scope.patient.patient_Id = response[0]["patient_Id"];
                            //RESTService.getResponse(URL.patient.updatePatient2.format($.param($scope.patient)));
                            //handler(response);
                            $scope.$state.reload();
                            $scope.cancel();
                        } else {
                            //toaster.pop("error", $translate.instant("business.patcase.ic_no_exists").format($scope.patient._user.icNo));
                            $button.button("reset");
                        }
                    });
                $button.button("reset");
            } else {
                // var param = $.param($scope.patient).replace(/null/gi, "");

                // update patient
                // RESTService.getResponse(URL.patient.updatePatient2.format(param)).then(
                //     function (response) {
                //         handler(response);
                //     });
                RESTService.postResponse(URL.patient.updatePatient2, $scope.patient).then(
                    function (response) {
                        handler(response);
                    });
            }
        };

        $scope.onCheckIcNo = function ($event, newValue, patientId) {
            var $me = $($event.currentTarget).css("border", "");

            if (undefined !== newValue) {
                RESTService.getResponse(URL.patient.checkIcNo.format(newValue, patientId || "")).then(
                    function (response) {
                        if (angular.isObject(response[0]) && true === response[0].exists) {
                            $me.css("border", "1px solid #b94a48");
                            toaster.pop("error", $translate.instant("business.patcase.ic_no_exists").format(newValue));
                        }
                        else {
                            // set value of _user from IcNo, by DongWeiyong
                            var birth_Year = "";
                            var birth_Month = "";
                            var gender = "";
                            if (newValue.length == 15) {
                                var tmpStr = newValue.substring(6, 12);
                                tmpStr = "19" + tmpStr;
                                birth_Year = tmpStr.substring(0, 4);
                                birth_Month = tmpStr.substring(4, 6);
                                gender = newValue.substring(13, 14);
                            }
                            else {
                                var tmpStr = newValue.substring(6, 14);
                                birth_Year = tmpStr.substring(0, 4);
                                birth_Month = tmpStr.substring(4, 6);
                                gender = newValue.substring(16, 17);
                            }

                            $scope.patient._user.birth_Year = birth_Year;
                            $scope.patient._user.birth_Month = birth_Month;
                            if (gender % 2 == 0) {
                                $scope.patient._user.gender = "female";
                            }
                            else {
                                $scope.patient._user.gender = "male";
                            }
                        }
                    });
            }
        };
        $scope.onEdit = function () {
            $scope.viewOnly = false;
            $scope.isEdit = true;
        };

        $scope.cancelPatient = function () {
            if ($rootScope.isSubmit) {
                $scope.$state.reload();
            }
            $scope.cancel();
        }
    }

// patient case
    function AddPatientCaseCtrl($scope, $rootScope, $modal, PatientCaseFactory, RESTService) {
        $scope.ArrPatCases = [];
        $scope.isAdd = false;
        $scope.diseaseSiteList = [];
        RESTService.getResponse('/rest//diseasesite/getDiseaseSiteList?').then(function (response) {
            $scope.diseaseSiteList = response;
        });

        $scope.createPatCase = function () {
            var patcase = {};
            patcase = PatientCaseFactory.SetPatientCase(patcase);
            var NoOfPatCase = $scope.ArrPatCases.length + 1;
            patcase.title = "新病例 " + NoOfPatCase;
            $scope.ArrPatCases.push(patcase);
            $scope.patient.canAddPatCase = false;
        };

        $scope.onChangeBmi = function ($event, item) {
            if (item.height > 0) {
                item.bmi = Math.round(item.weight * 10000 / item.height / item.height);
                if (item.bmi > 99) {
                    item.bmi = 99;
                }
            }
        }

        $scope.editPatientCase = function (item) {
            item.isedit = true;
        };

        $scope.cancelPatientCase = function (item) {
            if (!item.patCase_Id) {
                $scope.deletePatCase(item);
                $scope.patient.canAddPatCase = true;
            }
            else {
                item.isedit = false;
            }
        };

        $scope.cancelPatient = function () {
            if ($rootScope.isSubmit) {
                $scope.$state.reload();
                $rootScope.isSubmit = false;
            }
            $scope.cancel();
        }

        $scope.getPatientCases = function (patient_Id) {
            $scope.ArrPatCases = [];

            if (patient_Id > 0 && patient_Id != null) {
                var params = "patient_Id=" + patient_Id;

                PatientCaseFactory.getPage(params).then(function (response) {
                    if (undefined !== response) {
                        angular.forEach(response, function (item) {
                            var patcase = PatientCaseFactory.SetPatientCase(item);
                            var NoPatcase = response.indexOf(item) + 1;
                            patcase.isedit = false;
                            patcase.title = NoPatcase + "/ " + patcase.brief_Desc;
                            $scope.ArrPatCases.push(patcase);
                        });

                        if ($scope.ArrPatCases.length > 0) {
                            $scope.ArrPatCases[0].editable = true;
                            $scope.ArrPatCases[0].isedit = true;
                        }
                    }

                    if ($scope.ArrPatCases.length > 0) {
                        $scope.ArrPatCases[0].editable = true;
                        $scope.ArrPatCases[0].isedit = true;
                    }
                })
            }
        };

        $scope.savePatientCase = function (item) {
            item.patient_Id = $scope.patient ? $scope.patient.patient_Id : 0;
            if (item.patient_Id > 0) {
                PatientCaseFactory.savePatientCase(item).then(function (response) {
                    if (undefined !== response && response.length > 0) {
                        item.patCase_Id = response[0].patCase_Id;
                        $scope.getPatientCases(item.patient_Id);
                        item.canAddPatCase = true;
                        $rootScope.isSubmit = true;
                    }
                });
            }
            else {
                alert("Patient have not created yet")
            }
        };

        $scope.deletePatCase = function (patCase) {
            if (!patCase.patCase_Id) {
                $scope.ArrPatCases.splice($scope.ArrPatCases.indexOf(patCase), 1);
            }
        };

        // open upload image window
        $scope.openUploadImage = function (patCase) {
            var modalInstance = $modal.open({
                backdrop: "static",
                templateUrl: 'UploadImage.html',
                controller: 'UploadImageModalInstanceCtrl',
                size: 'md',
                resolve: {
                    items: function () {
                        return patCase;
                    }
                }
            });
            modalInstance.result.then(function (userId) {
                //ok click
            }, function () {
                //cancel
            });
        };

        $scope.deleteMediCase = function (patCase, mediCase) {
            var modalInstance = $modal.open({
                backdrop: 'static',
                templateUrl: 'DeleteMediCase.html',
                controller: 'ModalInstanceCtrl', size: 'md', resolve: {
                    items: function () {
                        return mediCase
                    }
                }
            });
            modalInstance.result.then(function () {
                RESTService.postResponse("/rest/medicase/deleteMediCase?", {mediCase_Id: mediCase.mediCase_Id}, true)
                    .then(function (response) {
                        if (response.code == 0) {
                            patCase._mediCases.splice(patCase._mediCases.indexOf(mediCase), 1);
                        }
                    });
            }, function () {
            })
        };

        $scope.moveUpMediCase = function (patCase, mediCase) {
            RESTService.postResponse("/rest/medicase/moveUpMediCase?", {mediCase_Id: mediCase.mediCase_Id}, true)
                .then(function (response) {
                    if (response.code == 0) {
                        patCase._mediCases = response.data;
                    }
                });
        };

        $scope.moveDownMediCase = function (patCase, mediCase) {
            RESTService.postResponse("/rest/medicase/moveDownMediCase?", {mediCase_Id: mediCase.mediCase_Id}, true)
                .then(function (response) {
                    if (response.code == 0) {
                        patCase._mediCases = response.data;
                    }
                });
        }

    }

    function PatientCaseFactory(RESTService) {
        var object = {};

        function filterValue(val, type) {
            var res = null;

            switch (type) {
                case "string":
                    res = (val) ? val.trim() : "";
                    break;
                case "number":
                    res = (val) ? val : "";
                    break;
                case "date":
                    res = (val) ? val : new Date();
                    break;
                default:
            }

            return res;
        }

        object.SetPatientCase = function (item) {
            var patientcase = {
                patCase_Id: filterValue(item.patCase_Id, "number"),
                patient_Id: filterValue(item.patient_Id, "number"),
                brief_Desc: filterValue(item.brief_Desc, "string"),
                waist_Pain: filterValue(item.waist_Pain, "string"),
                main_Desc: filterValue(item.main_Desc, "string"),
                blood_Pressure_High: filterValue(item.blood_Pressure_High, "number"),
                blood_Pressure_Low: filterValue(item.blood_Pressure_Low, "number"),
                weight: filterValue(item.weight, "number"),
                height: filterValue(item.height, "number"),
                body_Temp: filterValue(item.body_Temp, "number"),
                heart_Beat: filterValue(item.heart_Beat, "number"),
                breath_Int: filterValue(item.breath_Int, "number"),
                bmi: filterValue(item.bmi, "number"),
                updated: filterValue(item.updated, "date"),
                updatedF: moment(item.updated).format("YYYY-MM-DD  HH:mm:ss"),
                lower_Limb: filterValue(item.lower_Limb, "string"),
                lower_Limb_Muscle: filterValue(item.lower_Limb_Muscle, "string"),
                upper_Limb: filterValue(item.upper_Limb, "string"),
                spirit_State: filterValue(item.spirit_State, "string"),
                strength: filterValue(item.strength, "string"),
                appetite: filterValue(item.appetite, "string"),
                sleeping: filterValue(item.sleeping, "string"),
                weight_Change: filterValue(item.weight_Change, "number"),
                gatism_Handling: filterValue(item.gatism_Handling, "string"),
                method_Transport: filterValue(item.method_Transport, "string"),
                spine_Waist: filterValue(item.spine_Waist, "string"),
                spine_Waist_Angle: filterValue(item.spine_Waist_Angle, "number"),
                spine_Skin: filterValue(item.spine_Skin, "string"),
                spine_KnockPain: filterValue(item.spine_KnockPain, "string"),
                spine_KnockPain_No: filterValue(item.spine_KnockPain_No, "number"),
                _mediCases: item._mediCases
            };
            patientcase.disease_Site = '';
            patientcase.disease_Site_Array = (item._diseaseSites) ? item._diseaseSites : [];

            if (patientcase.patCase_Id == 0) // is New
            {
                patientcase.isNew = true;
                patientcase.isedit = true;
            }

            return patientcase;
        };

        object.getPage = function (param) {
            return RESTService.getResponse("/rest/patcase/getPatCases?" + param);
        };

        object.savePatientCase = function (item) {
            if (item.disease_Site_Array != null || item.disease_Site_Array != []) {
                angular.forEach(item.disease_Site_Array, function (disease) {
                    var prefix = ",";
                    if (item.disease_Site != '') {
                        item.disease_Site += prefix;
                    }
                    item.disease_Site += disease.desc;
                })
            }
            item.disease_Site_Array = null;
            if (item.patCase_Id > 0) {
                return RESTService.postResponse("/rest/patcase/updatePatCase?", item)
            }
            else {
                return RESTService.postResponse("/rest/patcase/createPatCase?", item)
            }
        };
        return object;
    }

    function PatientServReqController($scope, $translate, $modal, $timeout, RESTService, $filter) {
        $scope.ServReq = angular.extend({}, $scope.selected.item);
        $scope.flows = '';
        $scope.servReq = '';
        if ($scope.ServReq.servReq_Id == undefined) {
            $scope.ServReq.servReq_Id = '';
        }

        var loadServFlowData = function () {
            RESTService.getResponse("/rest/servreq/getServReq?servReq_Id=" + $scope.ServReq.servReq_Id + "&patient_Id=" + $scope.ServReq.patient_Id)
                .then(function (response) {
                    $scope.servReq = response[0];
                });
            RESTService.getResponse("/rest/servflow/getServFlows?servReq_Id=" + $scope.ServReq.servReq_Id + "&patient_Id=" + $scope.ServReq.patient_Id)
                .then(function (response) {
                    $scope.flows = response;
                });
        }
        $scope.init = function () {
            loadServFlowData();
        }

        $scope.diseaseSiteList = [];
        RESTService.getResponse('/rest//diseasesite/getDiseaseSiteList?').then(function (response) {
            $scope.diseaseSiteList = response;
        });

        // load data
        $scope.gender = [
            {
                value: "male",
                displayNameEn: $translate.instant('user.gender.male'),
                displayNameCn: $translate.instant('user.gender.male')
            },
            {
                value: "female",
                displayNameEn: $translate.instant('user.gender.female'),
                displayNameCn: $translate.instant('user.gender.female')
            }
        ];
        $scope.marriage = [
            {
                value: "single",
                displayNameEn: $translate.instant('user.marriage.single'),
                displayNameCn: $translate.instant('user.marriage.single')
            },
            {
                value: "married",
                displayNameEn: $translate.instant('user.marriage.married'),
                displayNameCn: $translate.instant('user.marriage.married')
            },
            {
                value: "widowed",
                displayNameEn: $translate.instant('user.marriage.widowed'),
                displayNameCn: $translate.instant('user.marriage.widowed')
            }
        ];
    }

// upload image
    angular.module('app').controller('UploadImageModalInstanceCtrl',
        function ($scope, $http, RESTService, AuthService, $modalInstance, items) { // based on modalInstance
            $scope.ok = function () {
                $scope.uploadImage(imageSrc);
            };
            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            }

            $scope.uploadImage = function (imageData) {
                // alert(imageData);
                var access_token = AuthService.loadData("_access_token");
                var urladdress = AuthService.getRsContext() + "/rest/medicase/createMediCase?" + "&access_token=" + access_token + "&patCase_Id=" + items.patCase_Id;
                RESTService.postHttp(urladdress, {base64Str: imageData}).then(function (response) {
                    if (response.code == 0) {
                        items._mediCases.push(response.data[0]);
                        $modalInstance.close();
                        console.log('上传成功');
                    }
                });
            };
        });

    angular.module('app')
        .directive('fileModel', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs, ngModel) {
                    var model = $parse(attrs.fileModel);
                    var modelSetter = model.assign;
                    element.bind('change', function (event) {
                        scope.$apply(function () {
                            modelSetter(scope, element[0].files[0]);
                        });
                        scope.file = (event.srcElement || event.target).files[0];
                        scope.getFile();
                    });
                }
            };
        }]);
    // ================================================
    (function (module) {
        //压缩
        function ImageCompress($q) {
            var _this = this;
            var compress = function (uri, options) {
                return _this._createImage(uri, options || {}, $q);
            };
            return compress;
        }

        ImageCompress.prototype._createImage = function (uri, options, $q) {
            this.options = angular.extend(options, {
                type: 'image/jpeg',
                quality: .5,
                maxWidth: 1000,
                maxHeight: 1000
            });

            var defer = $q.defer();
            var img = new Image();
            var _this = this;

            function tmpLoad() {
                var dt = defer.resolve(_this._drawImage(this));
                return dt;
            }

            img.onload = tmpLoad;
            img.src = uri;
            return defer.promise;
        };

        ImageCompress.prototype._drawImage = function (img, callback) {
            this.sw = img.width;
            this.sh = img.height;
            this.tw = img.width;
            this.th = img.height;

            this.scale = (this.tw / this.th).toFixed(2);

            if (this.sw > this.options.maxWidth) {
                this.sw = this.options.maxWidth;
                this.sh = Math.round(this.sw / this.scale);
            }

            if (this.sh > this.options.maxHeight) {
                this.sh = this.options.maxHeight;
                this.sw = Math.round(this.sh * this.scale);
            }

            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');

            canvas.width = this.sw;
            canvas.height = this.sh;

            // 旋转
            // function rotateImg(){
            //     var Orientation = null;
            //     EXIF.getData(img, function() {
            //         Orientation = EXIF.getTag(img, "Orientation");
            //         console.log('文件1:',img);
            //         console.log('拍摄方向:',Orientation);
            //     });
            //     if(Orientation != "" && Orientation != 1){
            //         alert('旋转处理');
            //         switch(Orientation){
            //             case 6://需要顺时针（向左）90度旋转
            //                 alert('需要顺时针（向左）90度旋转');
            //                 ctx.rotate(-90*Math.PI/180);
            //                 break;
            //             case 8://需要逆时针（向右）90度旋转
            //                 alert('需要顺时针（向右）90度旋转');
            //                 ctx.rotate(90*Math.PI/180);
            //                 break;
            //             case 3://需要180度旋转
            //                 alert('需要180度旋转');
            //                 ctx.rotate(-180deg);
            //                 break;
            //         }
            //     }
            // }


            ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh);

            var uri = canvas.toDataURL(this.options.type, this.options.quality);

            ctx.clearRect(0, 0, this.tw, this.th);
            canvas.width = 0;
            canvas.height = 0;
            canvas = null;

            return uri;
        };

        module.service("imageCompress", ["$q", ImageCompress]);
    }(angular.module("app")));
    // ================================================
    angular.module('app')
        .controller('UploaderController', function ($scope, fileReader, imageCompress) {
            $scope.getFile = function () {
                fileReader.readAsDataUrl($scope.file, $scope)
                    .then(function (result) {
                        var compress = imageCompress(result, { //图片url, 可以用base64
                            type: 'image/jpeg', //文件类型, 如 image/jpeg
                            quality: .5 //图片质量，范围 (0，1]，为1时不进行质量压缩
                        });
                        compress.then(function (dt) {
                            $scope.imageSrc = dt;
                            imageSrc = dt;
                        });
                    });
            };
        });

    angular.module('app')
        .factory('fileReader', ["$q", "$log", function ($q, $log) {
            var onLoad = function (reader, deferred, scope) {
                return function () {
                    scope.$apply(function () {
                        deferred.resolve(reader.result);
                    });
                };
            };
            var onError = function (reader, deferred, scope) {
                return function () {
                    scope.$apply(function () {
                        deferred.reject(reader.result);
                    });
                };
            };
            var getReader = function (deferred, scope) {
                var reader = new FileReader();
                reader.onload = onLoad(reader, deferred, scope);
                reader.onerror = onError(reader, deferred, scope);
                return reader;
            };
            var readAsDataURL = function (file, scope) {

                var deferred = $q.defer();
                var reader = getReader(deferred, scope);
                reader.readAsDataURL(file);
                return deferred.promise;
            };
            return {
                readAsDataUrl: readAsDataURL
            };
        }])

})(jQuery);

